package com.jdk.demo.asynchronousFileChannel.conpletionHandler获取锁;

import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

// CompletionHandler接口的使用
public class Test1 {

	public static void main(String[] args) throws Exception {
		Path path = Paths.get("E:/zsl/temp2.txt");
		AsynchronousFileChannel channel =  AsynchronousFileChannel.open(path, StandardOpenOption.WRITE);
		System.out.println("begin time=" + System.currentTimeMillis());
		// 先关闭channel，则下面获取锁就会触发failed
		// channel.close();
		channel.lock("我是附加值", new CompletionHandler<FileLock, String>() {
			@Override
			public void completed(FileLock result, String attachment) {
				try {
					System.out.println("public void completed(FileLock result, String attachment) attachment=" + attachment);
					result.release();
					channel.close();
					System.out.println("release and close");
				}catch (Exception e) {
					// TODO: handle exception
				}
			}

			@Override
			public void failed(Throwable exc, String attachment) {
				System.out.println("public void failed(Throwable exc, String attachment) attachment=" + attachment);
				System.out.println("getMessage=" + exc.getMessage());
			}
		});
		// 可以看到begin和end的时间非常接近，几乎是一样的，这就是异步的优势
		System.out.println("end time=" + System.currentTimeMillis());
		Thread.sleep(3000);
	}

}
